package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.dao.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Component
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> testDindAll() {
        return userMapper.selectList(null);

    }

    @Override
    public String login(User user) {
        String password = user.getPassword();
        String md5 = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5);
        QueryWrapper<User> queryWrapper = new QueryWrapper(user);
        List<User> userList = userMapper.selectList(queryWrapper);
        if(userList == null){
            return null;
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        return token;
    }

    @Override
    public PageResult getUserList(PageResult pageResult) {

        Page<User> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());

        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like(flag,"username", pageResult.getQuery());

        Page<User> Page = userMapper.selectPage(page, wrapper);

        pageResult.setRows(page.getRecords())
                .setTotal(page.getTotal());
        return pageResult;
    }

    @Override
    @Transactional
    public void updateStatus(User user) {
        userMapper.updateById(user);

    }

    @Override
    @Transactional
    public void addUser(User user) {
        String password = user.getPassword();
        String password1 = DigestUtils.md5DigestAsHex(password.getBytes())
                .toString().replace("-", "");
        user.setPassword(password1)
                .setStatus(true);
        userMapper.insert(user);
    }
    @Override
    public User findUserById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    @Transactional
    public void MedeleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void updateUser(User user) {

        userMapper.updateById(user);
    }
}
